package com.ape.mapsa.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.MenuModel;

import com.ape.mapsa.produccion.model.Cliente;
import com.ape.mapsa.produccion.service.IProduccionService;

@ManagedBean(name = "clientesMB")
@ViewScoped
public class ClienteBean extends BeanCRUD implements Serializable {
	private static final long serialVersionUID = -1567687802839693929L;
	private static final Logger log = Logger.getLogger(ClienteBean.class);

	@ManagedProperty(value = "#{produccionService}")
	private IProduccionService prodService;

	private List<Cliente> clientes;
	private List<Cliente> clientesFiltrados = new ArrayList<Cliente>();
	private Cliente selectedCliente = null;
	private boolean rowSelected = false;

	private Cliente result;

	private Cliente newCliente;

	private boolean showAbm;
	private boolean editing;

	@PostConstruct
	public void initialize() {
		log.info("Initializing CLIENTE BEAN");
		clientes = new ArrayList<Cliente>();
		newCliente = new Cliente();
		setClientes(prodService.getAllClientes());
		clientesFiltrados.addAll(clientes);
	}

	public void addCliente() {
		try {
			if (newCliente.getId() == null) {
				prodService.saveCliente(newCliente);
				clientes.add(newCliente);
				clientesFiltrados.add(newCliente);
			} else {
				prodService.updateClient(newCliente);
			}
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cliente guardado", newCliente.getNombre());
			FacesContext.getCurrentInstance().addMessage(null, msg);
			RequestContext.getCurrentInstance().update("addClienteForm:clientes:clientesTableID");
		} catch (Exception x) {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al guardar el cliente", newCliente.getNombre());
			FacesContext.getCurrentInstance().addMessage(null, msg);
			log.error(x);
		}

	}

	@Override
	public void edit(ActionEvent event) {
		log.info("Editando Cliente " + selectedCliente);
		newCliente = selectedCliente;
		if (newCliente != null) {
			setShowAbm(true);
			setEditing(true);
			RequestContext.getCurrentInstance().update("addClienteForm:abm_id");
			RequestContext.getCurrentInstance().scrollTo("addClienteForm:abm_id");
		} else {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciono nula", "Debe seleccionar un cliente para editar.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}

	@Override
	public void save(ActionEvent event) {
		addCliente();
	}

	@Override
	public void update(ActionEvent event) {
		// TODO Auto-generated method stub

	}

	@Override
	public void create(ActionEvent event) {
		log.info("Cliente nuevo");
		newCliente = new Cliente();
		setShowAbm(true);
		setEditing(false);
		RequestContext.getCurrentInstance().update("addClienteForm:abm_id");
		RequestContext.getCurrentInstance().scrollTo("addClienteForm:abm_id");
	}

	@Override
	public void delete(ActionEvent event) {
		log.info("Eliminando cliente " + selectedCliente);
		newCliente = selectedCliente;
		if (newCliente != null) {
			setShowAbm(false);
			setEditing(false);
			RequestContext.getCurrentInstance().update("addClienteForm:abm_id");
			prodService.deleteCliente(newCliente);
			RequestContext.getCurrentInstance().update("addClienteForm:clientes:clientesTableID");
		} else {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciono nula", "Debe seleccionar un color de la tabla.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}

	public void rowSelected(SelectEvent event) {
		log.info("cliente del evento " + event.getObject());
		log.info("cliente seleccionado " + selectedCliente.getNombre());
		setRowSelected(selectedCliente != null);
		result = selectedCliente;
	}

	public void getCliente(ActionEvent actionEvent) {
		result = selectedCliente;
	}

	public IProduccionService getProdService() {
		return prodService;
	}

	public void setProdService(IProduccionService prodService) {
		this.prodService = prodService;
	}

	public Cliente getNewCliente() {
		return newCliente;
	}

	public void setNewCliente(Cliente newCliente) {
		this.newCliente = newCliente;
	}

	public List<Cliente> getClientes() {
		return clientes;
	}

	public void setClientes(List<Cliente> clientes) {
		this.clientes = clientes;
	}

	@PreDestroy
	public void predestroy() {
		log.info("CLIENTE BEAN BEAN IS GOING TO BE DESTROYED");
	}

	public Cliente getSelectedCliente() {
		return selectedCliente;
	}

	public void setSelectedCliente(Cliente selectedCliente) {
		this.selectedCliente = selectedCliente;
	}

	public List<Cliente> getClientesFiltrados() {
		return clientesFiltrados;
	}

	public void setClientesFiltrados(List<Cliente> clientesFiltrados) {
		this.clientesFiltrados = clientesFiltrados;
	}

	public boolean isRowSelected() {
		return rowSelected;
	}

	public void setRowSelected(boolean rowSelected) {
		this.rowSelected = rowSelected;
	}

	public Cliente getResult() {
		log.debug("Devolviendo cliente " + result.getNombre());
		return result;
	}

	public void setResult(Cliente result) {
		this.result = result;
	}

	@Override
	public MenuModel getMenuModel() {
		return menuModel;
	}

	public boolean isShowAbm() {
		return showAbm;
	}

	public void setShowAbm(boolean showAbm) {
		this.showAbm = showAbm;
	}

	public boolean isEditing() {
		return editing;
	}

	public void setEditing(boolean editing) {
		this.editing = editing;
	}

}
